<template>
  <div>
    <modal-view ref="modalViewRef" width="600px" :before-submit="beforeSubmit" @close="close">
      <el-form ref="formRef" label-width="80px" :model="formData" :rules="rules" label-position="left" size="small">
        <el-tabs>
          <el-tab-pane label="基本配置">
            <div class="page-tab-body">
              <el-form-item label="编号">
                <el-input v-model="formData.Id" placeholder="自动生成" disabled></el-input>
              </el-form-item>
              <el-form-item label="头像">
                <upload-img :doc-type="docType" v-model="formData._profile">
                </upload-img>
              </el-form-item>
              <el-form-item label="名称" prop="Name">
                <el-input v-model="formData.Name"></el-input>
              </el-form-item>
              <el-form-item label="性别" prop="Sex">
                <el-radio-group v-model="formData.Sex">
                  <el-radio-button v-for="item of SEX.array" :label="item.code">
                    {{ item.name }}
                  </el-radio-button>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="手机号" prop="Phone">
                <el-input v-model="formData.Phone"></el-input>
              </el-form-item>

            </div>
          </el-tab-pane>
          <el-tab-pane label="绑定门店">
            <div class="page-tab-body" v-loading="cmpLoading">
              <data-view :header-btn="['delete']" v-model="cmpList" @delete-submit="getMenDian()">
                <template #headerBtnLeft>
                  <select-load style="margin-right: 10px;" placeholder="点击添加门店" popover-width="300px" is-paging
                    :remote-method="remoteMethod" @select="onSelect">
                    <template #table-column>
                      <el-table-column prop="Name" label="门店" min-width="100"></el-table-column>
                    </template>
                  </select-load>
                </template>
                <el-table-column type="selection" width="40" align="center" />
                <el-table-column type="index" width="50" label="#" />
                <el-table-column prop="Name" label="门店">
                </el-table-column>
              </data-view>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </modal-view>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import { queryGet } from "@/utils/api";
export default defineComponent({
  name: "BizUserModalView",
})
</script>

<script lang="ts" setup>
import { ref, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import ModalView from "@/components/ModalView";
import { appAction } from "@/store/app";
import { docType, BizUserDataClass } from "@/model/BizUser";
import { request } from "@/utils/axios";
import { UploadImg } from "@/components/UploadFile";
import { CmpDataClass } from "@/model/Cmp";
import SelectLoad from "@/components/SelectLoad";
import DataView from "@/components/DataView";
import { SEX } from "@/config/constVar";

let emit = defineEmits<{
  (e: "close"): void;
  (e: "submit"): void
}>()

/**
 * 弹框
 */
let modalViewRef = ref();

/**
 * 表单
 */
let formRef = ref();

/**
 * 表单
 */
let formData = ref<BizUserDataClass>(new BizUserDataClass({}));

/**
 * 表单验证
 */
let rules = reactive({
  Name: [{ required: true, message: '当前项为必填项', trigger: 'blur' }],
  Sex: [{ required: true, message: '当前项为必填项', trigger: 'change' }],
  Phone: [{ required: true, message: '当前项为必填项', trigger: 'blur' }],
})

/**
 * 页面展示
 */
function show(data?: any) {
  formData.value = new BizUserDataClass(data || {});

  if (formData.value.Id) {
    //获取对应的门店
    getMenDian();
  }

  /**
   * 打开页面
   */
  modalViewRef.value.show();
}

/**
 *  保存前校验
 */
function beforeSubmit(): Promise<void> {
  return new Promise((resolve, reject) => {
    formRef.value.validate()
      .then(() => {

        if (cmpList.value.length == 0) {
          ElMessage.error("请添加至少一个门店")
          reject();
          return;
        }

        let url = "";
        if (formData.value.Id) {
          //存在为修改
          url = "/" + docType + "/Update";

        } else {
          //不存在ID 为新增
          url = "/" + docType + "/Add";
        }

        //数据提交
        request(url, Object.assign({}, formData.value, {
          Cmps: cmpList.value.map(item => item.Id)
        }))
          .then(() => {
            ElMessage.success("表单数据保存成功");
            emit("submit");
            resolve();
          })
          .catch(() => {
            appAction.resetPageuuid();
            reject();
          })
      })
      .catch((e: any) => {
        ElMessage.error("表单字段存在错误")
        reject()
      })
  })
}

/**
 * 关闭页面
 */
function close() {
  emit("close")
}



/**
 * ====================
 *  门店信息
 * ====================
 */

/**
 * 门店列表
 */
let cmpList = ref<CmpDataClass[]>([]);

let cmpLoading = ref(false);

/**
 * 获取门店信息
 */

function getMenDian() {
  cmpLoading.value = true;
  queryGet({
    docType: "Cmp",
    actionType: "UserId",
    apiType: "SingleList"
  }, {
    Id: formData.value.Id
  })
    .then(res => {
      cmpList.value = res.map((item: any) => new CmpDataClass(item))
    })
    .finally(() => {
      cmpLoading.value = false;
    })
}

/**
 * 新增门店绑定
 */
function onSelect(row: CmpDataClass) {
  if (cmpList.value.findIndex(item => row.Id == item.Id) >= 0) {
    ElMessage.warning(`门店[${row.Name}]已添加`);
  } else {
    cmpList.value.push(row);
    // cmpLoading.value = true;
    // request("/BizUserCmp/Save", {
    //   "CmpId": row.Id, //门店编号
    //   "UserId": formData.value.Id //人员编号
    // })
    //   .then(() => {
    //     ElMessage.success("门店绑定成功");
    //   })
    //   .finally(() => {
    //     cmpLoading.value = false;
    //     getMenDian();
    //   })
  }
}

/**
 * 获取门店信息
 */
function remoteMethod(para: any): Promise<{ dataList: any[], total?: number }> {
  return new Promise((resolve, reject) => {
    queryGet({
      docType: "Cmp",
      actionType: "PageList",
      apiType: "PageList"
    }, {
      Searchv: para.search,
      Start: (para.page - 1) * para.limit,
      Limit: para.limit
    })
      .then((res) => {
        resolve({
          dataList: res.List.map((item: any) => {
            return new CmpDataClass(item);
          }),
          total: res.Total
        })
      })
      .catch(reject)
  })
}

/**
 * ====================
 *  页面初始化
 * ====================
 */

/**
 * 导出
 */
defineExpose({
  show
})
</script>

<style lang="less" scoped>
.page-tab-body {
  height: 350px;
  overflow: auto;
}
</style>